<script setup>
	import {defineProps, toRefs, reactive, ref} from "vue"

	import {useStore} from 'vuex'
	import {ElMessage} from "element-plus"

	const store = useStore()
  const emits = defineEmits(['updatePics', 'deletePics'])

  const props = defineProps({
		pics: Array,
		limit: {type: Number, default: 9}
	})
	const {pics, limit} = toRefs(props)

	const viewData = reactive({
		action: 'http://127.0.0.1:9999/image/uploadImages',
		dialogVisible: false,
		dialogImageUrl: ''
	})
	const handleSuccess = (res) => {
    emits('updatePics', res)
  }

	const handlePreview = (uploadFile) => {
		viewData.dialogImageUrl = uploadFile.url
		viewData.dialogVisible = true
	}
	const handleExceed = () => {
		ElMessage({type: 'error', message: '超出数量或大小限制！'})
	}
  const handleRemove = (file) => {
    const newFileUrl = file.url.replace(store.getters.imageUrl, '');
    const index = pics.value.findIndex(pic => pic.url === file.url);
    if (index !== -1) {
      pics.value.splice(index, 1);
    }
    emits('deletePics', newFileUrl);
  }
</script>

<template>
	<el-upload
			v-model:file-list="pics"
			:action=viewData.action
			:headers=viewData.headers
			name="pics"
			multiple
			list-type="picture-card"
			:on-preview="handlePreview"
			:on-success="handleSuccess"
			:on-exceed="handleExceed"
      :on-remove="handleRemove"
      :limit="limit"
	>
		<el-icon>
			<Plus/>
		</el-icon>
	</el-upload>

	<el-dialog v-model="viewData.dialogVisible">
		<img w-full :src="viewData.dialogImageUrl" alt="Preview Image"/>
	</el-dialog>
</template>
